package com.tistory.admin.common.util;

import java.util.*;
import java.io.*;

import javax.mail.*;
import javax.mail.internet.*;
import javax.activation.*;
import javax.mail.event.*;

public class PostMan  implements ConnectionListener, TransportListener{

    public static void main(String[] args) {
            

            String to = "jade.kimhs@gmail.com";
            String from = "khs7999@naver.com";
            String host = "localhost";
            String filename = "테스트";
            String bcc = "ienvyou@javapattern.info";
            boolean debug = true;
            String msgText1 = "보내졌습니까?\n";
            String subject = "파일보내기 예제";
            
            // create some properties and get the default Session
            Properties props = System.getProperties();
            props.put("mail.smtp.host", host);
            props.put("mail.smtp.auth" , "true"); //아주 중요 없으면 인증을 시도할수가 없다.
            
            Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            
            PostMan sf = new PostMan();
            sf.go(session, to, bcc, from, subject, msgText1, filename );
    }

    public void go(Session session, 
                        String to, 
                        String bccc, 
                        String from, 
                        String subject, 
                        String msgText1, 
                        String filename){
            Transport trans = null;
            try {
                // create a message
                MimeMessage msg = new MimeMessage(session);
                msg.setFrom(new InternetAddress(from));
                InternetAddress[] address = {new InternetAddress(to)};
                InternetAddress [] cc = {new InternetAddress("ienvyou@javapattern.info")};
                InternetAddress [] bcc = {new InternetAddress("ienvyou@javapattern.info")};
                msg.setRecipients(Message.RecipientType.TO, address);
                msg.setRecipients(Message.RecipientType.CC, cc);
                msg.setRecipients(Message.RecipientType.BCC, bcc);
                msg.setSubject(subject);

                // create and fill the first message part
                MimeBodyPart mbp1 = new MimeBodyPart();
                mbp1.setText(msgText1);

                // create the second message part
                MimeBodyPart mbp2 = new MimeBodyPart();

                    // attach the file to the message
                FileDataSource fds = new FileDataSource(filename);

                mbp2.setDataHandler(new DataHandler(fds));
            // 헤더에 파일이름을 세팅할때 base64형태로 반드시.
                mbp2.setFileName(MimeUtility.encodeText(fds.getName(), "euc-kr","B"));  

                // create the Multipart and its parts to it
                Multipart mp = new MimeMultipart();
                mp.addBodyPart(mbp1);
                mp.addBodyPart(mbp2);

                // add the Multipart to the message
                msg.setContent(mp);

                // set the Date: header
                msg.setSentDate(new Date());
                
        /************** Carouser Adding *************************************/
                msg.saveChanges(); // msg객체에서 데이터를 보낼수 있도록 속성변경

                // 인증을 시도하도록 한다.
                trans = session.getTransport(address[0]);

                // register ourselves as listener for ConnectionEvents 
                // and TransportEvents
                trans.addConnectionListener(this);
                trans.addTransportListener(this);


                 // connect the transport
                trans.connect("openitech.co.kr","ienvyou","0000");
               

                // send the message
                //Transport.send(msg);
                trans.sendMessage(msg, address);
                
            } catch (Exception mex) {
                mex.printStackTrace();
                
            } finally {
                try{
                    trans.close();
                }catch(MessagingException e){}
            }
    }

     // implement ConnectionListener interface
    public void opened(ConnectionEvent e) {
        System.out.println(">>> ConnectionListener.opened()");
    }
    public void disconnected(ConnectionEvent e) {}
    public void closed(ConnectionEvent e) {
        System.out.println(">>> ConnectionListener.closed()");
    }

    // implement TransportListener interface
    public void messageDelivered(TransportEvent e) {
        System.out.print(">>> TransportListener.messageDelivered().");
        System.out.println(" Valid Addresses:");
        Address[] valid = e.getValidSentAddresses();
        if (valid != null) {
            for (int i = 0; i < valid.length; i++) 
            System.out.println("    " + valid[i]);
        }
    }
    public void messageNotDelivered(TransportEvent e) {
        System.out.print(">>> TransportListener.messageNotDelivered().");
        System.out.println(" Invalid Addresses:");
        Address[] invalid = e.getInvalidAddresses();
        if (invalid != null) {
            for (int i = 0; i < invalid.length; i++) 
            System.out.println("    " + invalid[i]);
        }
    }
    public void messagePartiallyDelivered(TransportEvent e) {
    // SMTPTransport doesn't partially deliver msgs
    }
}


